
package com.kugou.game.sdk.utils;

import com.kugou.download.DownloadFile;
import com.kugou.download.FileDownloader;
import com.kugou.download.manager.ParamsWrapper;
import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.download.DownloadOperator;
import com.kugou.game.sdk.download.DownloadServiceUtil;
import com.kugou.game.sdk.entity.AppInfo;
import com.kugou.game.sdk.ui.activity.GameCenterActivity;
import com.kugou.game.sdk.ui.activity.LoginActivity;
import com.kugou.game.sdk.ui.activity.RegisterByPhoneActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

/**
 * 描述:本地方法管理类（提供给JS调用）
 * 
 * @author liux
 * @since 2014-10-30 上午10:22:06
 */
public class AndroidMethodProvider {

    private static final String TAG = "AndroidMethodProvider";

    private GameCenterActivity mActivity;

    private WebView mWeb;

    public AndroidMethodProvider(GameCenterActivity activity, WebView view) {
        // LogUtil.d(TAG, "AndroidMethodProvider()-->调用构造函数");
        this.mActivity = activity;
        this.mWeb = view;
    }

    private boolean checkActivityDestroy() {
        return mActivity == null || mActivity.isFinishing() || mActivity.isActivityDestroy();
    }

    /**
     * 获取设备信息
     * 
     * @return json
     */
    @JavascriptInterface
    public String getDeviceInfo() {
        LogUtil.d(TAG, "getDeviceInfo()");
        try {
            JSONObject obj = new JSONObject();
            obj.put("imei", AppUtil.getMachineSN(mActivity));
            obj.put("clientVer", SDKControler.getSDKVersionName());
            obj.put("from", 5);
            obj.put("model", AppUtil.getPhoneModel());
            obj.put("systemVer", AppUtil.getSysVersionName());
            obj.put("resolution", AppUtil.getScreenSizeStr(mActivity));
            obj.put("spid", AppUtil.getMNCNum(mActivity));
            obj.put("mid", AppUtil.getKugouMID(mActivity));
            obj.put("uuid", AppUtil.getKugouUUID(mActivity));
            return obj.toString().replace("\\", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取网络类型
     * 
     * @return int 0：无网络，1：wifi，2：2G，3：3G，4：4G
     */
    @JavascriptInterface
    public int getNetType() {
        LogUtil.d(TAG, "getNetType()");
        return AppUtil.getNetworkType(mActivity);
    }

    /**
     * 初始化应用列表状态
     * 
     * @param jsonAppList
     */
    @JavascriptInterface
    public void initAppState(String jsonAppList) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "initAppState()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "initAppState()---传入：>" + jsonAppList);
        final String appStateData = getAppState(jsonAppList);
        LogUtil.d(TAG, "initAppState()---返回：>" + appStateData);
        // mWeb.loadUrl("javascript:initAppStateCallBack('" + appStateData +
        // "')");
        mActivity.runOnUiThread(new Runnable() {
            public void run() {
                if (mWeb != null && !TextUtils.isEmpty(appStateData)) {
                    mWeb.loadUrl("javascript:initAppStateCallBack('" + appStateData + "')");
                }
            }
        });
    }

    /**
     * 获取应用状态
     * 
     * @param jsonAppList
     * @return String
     */
    @JavascriptInterface
    public String getAppState(String jsonAppList) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "getAppState()---activity has destroy.");
            return null;
        }
        LogUtil.d(TAG, "getAppState()---传入：>" + jsonAppList);
        String appStateData = "";
        try {
            if (!TextUtils.isEmpty(jsonAppList)) {
                JSONArray array = new JSONArray(jsonAppList);
                int size = array.length();
                if (size > 0) {
                    // 对数据进行处理
                    JSONArray data = new JSONArray();
                    for (int i = 0; i < size; i++) {
                        JSONObject temp = array.getJSONObject(i);
                        int gameid = temp.getInt("gameid");
                        String packageName = temp.getString("packagename");
                        String fileHash = temp.getString("filehash");
                        int versioncode = -1;
                        try {
                            versioncode = temp.getInt("versioncode");
                        } catch (Exception e) {
                        }
                        // 对结果进行组装
                        JSONObject obj = handleAppState(packageName, fileHash, gameid, versioncode);
                        data.put(obj);
                    }
                    appStateData = data.toString().replace("\\", "");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtil.d(TAG, "getAppState()---返回：>" + appStateData);
        return appStateData;
    }

    /**
     * 组装App的状态
     * 
     * @param packageName
     * @param fileHash
     * @param gameid
     * @return JSONObject
     */
    @SuppressLint("NewApi")
    private JSONObject handleAppState(String packageName, String fileHash, int gameid,
            int versioncode) {
        JSONObject obj = new JSONObject();
        try {
            // 状态，0:未下载，1:已下载但未安装，2:已安装，3:正在下载，4：正在等待队列中,5:继续下载，6：正在安装
            int state = 0;
            // app版本号
            int versionCode = -1;
            // 下载进度
            String progress = "";
            // 下载速度
            String speed = "";
            // 安装时间(时间戳)
            String installTime = "0";
            // 下载完成时间
            String downloadedTime = "0";
            // 已下载文件大小
            long readsize = 0;
            // 总文件大小
            long filesize = 0;

            boolean installed = AppUtil.checkAppExistSimple(mActivity, packageName);
            DownloadFile file = DownloadServiceUtil.getDownloadFileFromCache(fileHash);

            if (installed) {// 已安装
                try {
                    PackageInfo info = mActivity.getPackageManager().getPackageInfo(packageName, 0);
                    if (file != null) {// 有下载记录信息
                        if (file.getState() == FileDownloader.FINISH) {// 已下载完
                            if (versioncode != -1 && versioncode > info.versionCode) {
                                // 已下载了升级安装包，但未安装
                                state = 1;
                            } else {
                                state = 2;
                            }
                            versionCode = info.versionCode;
                            installTime = info.firstInstallTime / 1000l + "";
                        } else {
                            if (file.getHaveRead() > 0) {// 已经开始升级，但还未升级完成
                                state = 5;
                                progress = DownloadHelper.getDownloadingProgress(file) + "";
                                readsize = file.getHaveRead();
                                filesize = file.getFileSize();
                            } else {// 还未开始升级
                                state = 2;
                                versionCode = info.versionCode;
                                installTime = info.firstInstallTime / 1000l + "";
                            }
                        }
                    } else {
                        state = 2;
                        versionCode = info.versionCode;
                        installTime = info.firstInstallTime / 1000l + "";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (file != null) {
                    if (DownloadServiceUtil.isDownloading(fileHash)) {// 正在下载
                        state = 3;
                        progress = DownloadHelper.getDownloadingProgress(file) + "";
                        speed = file.getStatis().getCurrentSpeed() + "";
                    } else if (DownloadServiceUtil.isInWaittingQueue(fileHash)) {// 正在队列中等待
                        state = 4;
                        progress = DownloadHelper.getDownloadingProgress(file) + "";
                    } else if (InstallHelper.getInstance().isInstalling(packageName)) {// 是否正在安装
                        state = 6;
                    } else if (file.getState() == FileDownloader.FINISH) {// 下载完成未安装
                        if (FileUtil.isFileExist(file.getFilePath())) {// 下载完成且安装包未删除
                            state = 1;
                            DownloadFile temp = DownloadOperator.getInstance().query(fileHash);
                            if (temp != null && !TextUtils.isEmpty(temp.getExt8())) {
                                downloadedTime = temp.getExt8();
                            }
                        } else {
                            state = 0;
                        }
                    } else {// 暂停状态
                        state = 5;
                        progress = DownloadHelper.getDownloadingProgress(file) + "";
                    }
                    readsize = file.getHaveRead();
                    filesize = file.getFileSize();
                }
            }

            obj.put("gameid", gameid);
            obj.put("state", state);
            obj.put("versionCode", versionCode);
            obj.put("progress", progress);
            obj.put("speed", speed);
            obj.put("firstInstallTime", installTime);
            obj.put("downloadTime", downloadedTime);
            obj.put("readsize", readsize);
            obj.put("filesize", filesize);
            obj.put("filehash", fileHash);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 启动应用
     * 
     * @param packageName 应用包名
     */
    @JavascriptInterface
    public void openApp(String packageName) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "openApp()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "openApp()--->" + packageName);
        AppUtil.openApp(mActivity, packageName);

    }

    /**
     * 打开系统默认浏览器
     * 
     * @param url 链接地址
     */
    @JavascriptInterface
    public void openBrowser(String url) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "openBrowser()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "openBrowser()--->" + url);
        AppUtil.openNetUrl(url, mActivity);
    }

    /**
     * 安装应用
     * 
     * @param filehash
     * @return int 默认0；1安装文件不存在；2安装文件错误
     */
    @JavascriptInterface
    public int installApp(String filehash) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "installApp()---activity has destroy.");
            return 2;
        }
        LogUtil.d(TAG, "installApp()--->" + filehash);
        DownloadFile file = DownloadOperator.getInstance().query(filehash);
        LogUtil.d(TAG, "installApp()--->file=null--" + (file == null));
        if (file != null) {
            String filePath = file.getFilePath();
            if (!FileUtil.isFileExist(filePath)) {
                // 删除该条应用的本地记录和缓存信息
                DownloadOperator.getInstance().delete(filehash);
                DownloadServiceUtil.removeDownloadFileFromCache(filehash);
                return 1;
            } else {
                if (filePath.endsWith(FileDownloader.TEMP_FILE_EXT_NAME)) {
                    String newFilePath = filePath.replace(FileDownloader.TEMP_FILE_EXT_NAME, "");
                    FileUtil.rename(filePath, newFilePath);
                    filePath = newFilePath;
                }

                LogUtil.d(TAG, "installApp()--->filePath-" + filePath);
                if (mActivity.getPackageManager().getPackageArchiveInfo(filePath, 0) == null) {
                    return 2;
                } else {
                    InstallHelper.getInstance().install(filePath);
                }
            }
        }
        return 0;
    }

    /**
     * 开始下载
     * 
     * @param jsonAppInfo
     * @return int 1开始下载，0取消下载
     */
    @JavascriptInterface
    public int startDownload(String jsonAppInfo) {
        LogUtil.d(TAG, "startDownload()--->" + jsonAppInfo);
        try {
            JSONObject obj = new JSONObject(jsonAppInfo);
            AppInfo info = new AppInfo();
            info.setGameid(obj.getInt("gameid"));
            info.setAppName(obj.getString("gamename"));
            String fileHash = obj.getString("filehash");
            info.setFilehash(fileHash);
            info.setPackageName(obj.getString("packagename"));
            info.setFileSize(obj.getLong("fileSize"));
            info.setDownloadUrl(obj.getString("downloadUrl"));
            info.setVersionCode(obj.getInt("versioncode"));
            info.setVersionName(obj.getString("versionName"));
            info.setDownloadSourceId(obj.getInt("positionid"));
            info.setNeedAutoDownload(1);
            // info.setStatparams(obj.getString("statparams"));
            ParamsWrapper params = DownloadHelper.getParamsWrapperFromAppinfo(info);
            // 更新数据库自动下载标识位->需要自动下载
            DownloadOperator.getInstance().updateAutoDownloadFlag(fileHash, 1);
            DownloadHelper.download(params, null);
            return 1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 停止下载
     * 
     * @param filehash
     */
    @JavascriptInterface
    public void stopDownload(String filehash) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "stopDownload()---activity has destroy.");
            return;
        }

        if (TextUtils.isEmpty(filehash)) {
            return;
        }
        mActivity.stopDownload(filehash);
    }

    /**
     * 删除下载
     * 
     * @param filehash
     */
    @JavascriptInterface
    public void deleteDownload(String filehash) {
        LogUtil.d(TAG, "deleteDownload()--->" + filehash);
        if (TextUtils.isEmpty(filehash)) {
            return;
        }
        DownloadFile file = DownloadOperator.getInstance().query(filehash);
        if (file != null) {
            AppUtil.deleteDownloadFile(file, true);
        }
    }

    /**
     * 复制文本
     * 
     * @param str
     * @return 1成功，0失败
     */
    @JavascriptInterface
    public int copyText(String str) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "copyText()---activity has destroy.");
            return 0;
        }
        LogUtil.d(TAG, "copyText()--->" + str);
        try {
            ClipboardManager cManager = (ClipboardManager) mActivity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            cManager.setText(str);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 返回上一页
     */
    @JavascriptInterface
    public void goBack() {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "goBack()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "goBack()");
        mActivity.finish();
    }

    /**
     * 新界面打开链接
     * 
     * @param url
     */
    @JavascriptInterface
    public void openUrl(String url) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "openUrl()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "openUrl()-->" + url);
        Intent intent = new Intent(mActivity, GameCenterActivity.class);
        intent.putExtra(GameCenterActivity.URL_KEY, url);
        mActivity.startActivity(intent);
    }

    /**
     * 关闭游戏中心
     */
    @JavascriptInterface
    public void closeGameCenter() {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "closeGameCenter()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "closeGameCenter()");
        Intent intent = new Intent(SDKActions.ACTION_CLOSE_GAME_CENTER);
        mActivity.sendBroadcast(intent);
    }

    /**
     * 取消loading，显示页面
     */
    @JavascriptInterface
    public void showPage() {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "showPage()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "showPage()");
        mActivity.showPageAfterStartLoadPage();
    }

    /**
     * 启动拨打电话页面
     * 
     * @param phoneNum
     */
    @JavascriptInterface
    public void callPhone(String phoneNum) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "callPhone()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "callPhone()-->" + phoneNum);
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri uri = Uri.parse("tel:" + phoneNum);
            intent.setData(uri);
            mActivity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户信息
     * 
     * @return
     */
    @JavascriptInterface
    public String getUserInfo() {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "getUserInfo()---activity has destroy.");
            return null;
        }
        LogUtil.d(TAG, "getUserInfo()");

        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user != null) {
            try {
                JSONObject obj = new JSONObject();
                obj.put("userid", user.getKugouid());
                obj.put("username", user.getAccountName());
                obj.put("headurl", "");
                obj.put("token", user.getKugouToken());
                obj.put("userType", user.isRegistered() ? 1 : 2);
                obj.put("clientAppid", SDKControler.getAppId());
                return obj.toString().replace("\\", "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 调用登录界面
     * 
     * @param source 调用者来源
     */
    @JavascriptInterface
    public void invokeLogin(String source) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "invokeLogin()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "invokeLogin()");

        // 进入登录界面
        Intent intent = new Intent(mActivity, LoginActivity.class);
        intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                BaseCommonTitleFragmentActivity.FROM_GAME_CENTER);
        mActivity.setSource(source);
        mActivity.startActivity(intent);
    }

    /**
     * 调用注册界面（手机注册）
     * 
     * @param source 调用者来源
     */
    @JavascriptInterface
    public void invokeRegister(String source) {
        if (checkActivityDestroy()) {
            LogUtil.d(TAG, "invokeRegister()---activity has destroy.");
            return;
        }
        LogUtil.d(TAG, "invokeRegister()");

        // 进入一键注册（手机注册）界面
        Intent intent = new Intent(mActivity, RegisterByPhoneActivity.class);
        intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                BaseCommonTitleFragmentActivity.FROM_GAME_CENTER);
        mActivity.setSource(source);
        mActivity.startActivity(intent);
    }
}
